/*
 * Copyright (c) 2018-2024 北京华恒盛世科技有限公司
 * QUICKPOOL is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *     http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
*/

#include "subcmd.h"

static void switchjob_usage(const char *);

/**
 * @brief       qp job switch handler, to switch job from one queue to another.
 *
 * @param[in]   argc          #1: number of input argument
 * @param[in]   argv          #2: string array of the input argument
 *
 * @retval      0             #1: succeed
 * @retval      1             #2: input option is wrong or kind of input argument not specified
 * @retval      2             #3: argument has syntax error
 * @retval      3             #4: failed to switch the job
 * @retval      4             #5: not enough memory
 */
int
cmd_switch_job(int argc, char **argv)
{
    char *strQueue=NULL, *strUser=NULL, *strNode=NULL, *strJobName=NULL;
    while (TRUE) {
        int option_index = 0;
        static struct option long_options[] = {
            {"help", no_argument, 0, 'h'},
            {"node", required_argument, 0, 'm'},
            {"queue", required_argument, 0, 'q'},
            {"user", required_argument, 0, 'u'},
            {"jobname", required_argument, 0, 'J'},
            {NULL, 0, 0, 0}
        };

        int opt;
        opt = getopt_long(argc, argv, "hJ:q:u:m:", long_options, &option_index);
        if (-1 == opt) {
            break;
        }

        switch (opt) {
        case 'm':
            if (NULL != strNode) {
                fprintf(stderr, "Do not specify -m/--node option for multiple times.\n");
                switchjob_usage(argv[0]);
                exit(1);
            }

            if (0 >= strlen(optarg)) {
                fprintf(stderr, "Specify a node name with -m/--node option.\n");
                switchjob_usage(argv[0]);
                exit(1);
            }

            strNode = optarg;
            break;
        case 'q':
            if (NULL != strQueue) {
                fprintf(stderr, "Do not specify -q/--queue option for multiple times.\n");
                switchjob_usage(argv[0]);
                exit(1);
            }

            if (0 >= strlen(optarg)) {
                fprintf(stderr, "Specify a queue name with -q/--queue option.\n");
                switchjob_usage(argv[0]);
                exit(1);
            }

            strQueue = optarg;
            break;
        case 'u':
            if (NULL != strUser) {
                fprintf(stderr, "Do not specify -u/--user option for multiple times.\n");
                switchjob_usage(argv[0]);
                exit(1);
            }

            if (0 >= strlen(optarg)) {
                fprintf(stderr, "Specify a user name with -u/--user option.\n");
                switchjob_usage(argv[0]);
                exit(1);
            }

            strUser = optarg;
            break;
        case 'J':
            if (NULL != strJobName) {
                fprintf(stderr, "Do not specify -J/--jobname option for multiple times.\n");
                switchjob_usage(argv[0]);
                exit(1);
            }

            if (0 >= strlen(optarg)) {
                fprintf(stderr, "Specify a job name with -J/--jobname option.\n");
                switchjob_usage(argv[0]);
                exit(1);
            }

            strJobName = optarg;
            break;
        case 'h':
            switchjob_usage(argv[0]);
            exit(0);
        case '?':
        default:
            switchjob_usage(argv[0]);
            exit(1);
        }
    }

    char *strToQueue=NULL;
    if (argc >= optind + 1) {
        strToQueue = argv[optind];
        optind++;
    }

    if (NULL == strToQueue) {
        fprintf(stderr, "Must specify the destination queue.\n");
        switchjob_usage(argv[0]);
        exit(1);
    }

    struct request switchRequest;
    memset(&switchRequest, 0, sizeof(struct request));

    int numJobIds;
    JOBID_T *jobIds = NULL;
    numJobIds = get_jobids_fromargv(argc, argv, &jobIds);
    if (0 < numJobIds) { // specified job id, ignore -m, -u -q and -J options.

        switchRequest.number = 2;
        switchRequest.keyvalues = (struct keyvalue *)calloc(2, sizeof(struct keyvalue));
        if (NULL == switchRequest.keyvalues) {
            fprintf(stderr, "calloc(%ld) failed due to %m.\n",
                    switchRequest.number*sizeof(struct keyvalue));
            exit(4);
        }

        unsigned int size = numJobIds*sizeof(JOBID_T) + 10;
        switchRequest.keyvalues[0].key = REQUEST_KEY_JOBIDS;
        switchRequest.keyvalues[0].value = (char *)calloc(size+1, sizeof(char));
        if (NULL == switchRequest.keyvalues[0].value) {
            fprintf(stderr, "calloc(%d) failed due to %m.\n", size);
            exit(4);
        }

        int i;
        for (i = 0; i < numJobIds; i++) {
            if (0 == i) {
                snprintf(switchRequest.keyvalues[0].value, size, "%lld", jobIds[i]);
                continue;
            }

            unsigned int lenValue;
            lenValue = strlen(switchRequest.keyvalues[0].value);
            snprintf(switchRequest.keyvalues[0].value+lenValue, size, " %lld", jobIds[i]);
        }

        switchRequest.keyvalues[1].key = REQUEST_KEY_NAMES;
        switchRequest.keyvalues[1].value = copy_string(strToQueue);

        FREEUP(jobIds);
    } else {
        unsigned int num = 1; //toqueue

        if (NULL != strQueue) {
            num ++;
        }

        if (NULL != strNode) {
            num ++;
        }

        if (NULL != strUser) {
            num ++;
        }

        if (NULL != strJobName) {
            num ++;
        }

        if (1 == num) {
            fprintf(stderr, "Job ID or one of '-m/--node', '-u/--user' '-q/--queue' and '-J/--jobname' must be specified.\n");
            switchjob_usage(argv[0]);
            exit(1);
        }

        if (NULL == strUser) { //If not specify -u, use my name.
            num ++;
        }

        switchRequest.number = num;
        switchRequest.keyvalues = (struct keyvalue *)calloc(num, sizeof(struct keyvalue));
        if (NULL == switchRequest.keyvalues) {
            fprintf(stderr, "calloc(%ld) failed due to %m.\n",
                    switchRequest.number*sizeof(struct keyvalue));
            exit(4);
        }

        num = 0;
        if (NULL != strQueue) {
            switchRequest.keyvalues[num].key = REQUEST_KEY_QUEUENAME;
            switchRequest.keyvalues[num].value = copy_string(strQueue);
            num ++;
        }

        if (NULL != strNode) {
            switchRequest.keyvalues[num].key = REQUEST_KEY_HOSTNAME;
            switchRequest.keyvalues[num].value = copy_string(strNode);
            num ++;
        }

        if (NULL != strJobName) {
            switchRequest.keyvalues[num].key = REQUEST_KEY_JOBNAME;
            switchRequest.keyvalues[num].value = copy_string(strJobName);
            num ++;
        }

        switchRequest.keyvalues[num].key = REQUEST_KEY_USERNAME;
        if (NULL == strUser) {
            switchRequest.keyvalues[num].value = getmy_uname();
        } else {
            switchRequest.keyvalues[num].value = copy_string(strUser);
        }
        num ++;

        switchRequest.keyvalues[num].key = REQUEST_KEY_NAMES;
        switchRequest.keyvalues[num].value = copy_string(strToQueue);
        num ++;
    }

    struct QuickPoolJobReply *jobReply;
    jobReply = client_switchjob(&switchRequest, NULL);
    if (NULL == jobReply) {

        gf_xdr_free(gf_xdr_request, &switchRequest);
        fprintf(stderr, "Faild to switch job due to above reason.\n");

        exit(3);
    }

    gf_xdr_free(gf_xdr_request, &switchRequest);

    unsigned int i;
    for (i = 0; i < jobReply->num_job; i++) {
        char strJobId[32];

        fprintf(stdout, "Job <%s> is switched to queue <%s>.\n",
                jobid_2string(jobReply->jobIDs[i], strJobId), strToQueue);
    }

    for (i = 0; i < jobReply->num_error; i++) {
        fprintf(stderr, "%s\n", jobReply->error_messages[i]);
    }

    if (0 < jobReply->num_error) {
        gf_xdr_free(libxdr_job_reply, jobReply);
        FREEUP(jobReply);
        exit(3);
    }

    gf_xdr_free(libxdr_job_reply, jobReply);
    FREEUP(jobReply);

    exit(0);
} // end function cmd_switch_job

static void
switchjob_usage(const char *cmd)
{
    fprintf(stdout, "qp job %s usage: [-h, --help]", cmd);
    fprintf(stdout, "[-q, --queue queue_name] [-u, --user user_name|all]");
    fprintf(stdout, "\n\t\t     [-m, --node host_name] [-J, --jobname job_name]");
    fprintf(stdout, " dest_queue [jobId | \"jobId[idxList]\" ...]\n");

    return;
}
